package com.gitee.wsl.func.factory.sample

import com.gitee.wsl.func.factory.Factory

/**
 * Factory implementation that returns the same constant each time.
 *
 *
 * No check is made that the object is immutable. In general, only immutable
 * objects should use the constant factory. Mutable objects should
 * use the prototype factory.
 *
 *
 * @param <T> the type of results supplied by this supplier.
 * @since 3.0
</T> */
class ConstantFactory<T>(
    /** The closures to call in turn  */
    val constant: T?,
) : Factory<T?> {
    /**
     * Gets the constant.
     *
     * @return the constant
     * @since 3.1
     */

    /**
     * Always return constant.
     *
     * @return the stored constant value
     */
    public override fun create(): T? {
        return this.constant
    }

    companion object {

        /** Returns null each time  */
        // The null factory works for all object types
        val NULL_INSTANCE = ConstantFactory<Nothing>(null)

        /**
         * Factory method that performs validation.
         *
         * @param <T>  the type of the constant
         * @param constantToReturn  the constant object to return each time in the factory
         * @return the `constant` factory.
        </T> */
        fun <T> constantFactory(constantToReturn: T?): Factory<T?> {
            if (constantToReturn == null) {
                return NULL_INSTANCE as Factory<T?>
            }
            return ConstantFactory(constantToReturn)
        }
    }
}
